package kr.blogspot.stiner01.moduletutorial;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;

public class MultiTouchTest extends Activity implements OnTouchListener
{
    private StringBuilder _builder = new StringBuilder();
    private TextView _textView = null;
    
    float[] _x = new float[10];
    float[] _y = new float[10];
    boolean[] _touched = new boolean[10];
    
    private void updateTextView()
    {
        _builder.setLength(0);
        for (int i = 0; i < 10; i++)
        {
            _builder.append(_touched[i]);
            _builder.append(", ");
            _builder.append(_x[i]);
            _builder.append(", ");
            _builder.append(_y[i]);
            _builder.append("\n");
        }
        
        _textView.setText(_builder.toString());
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        _textView = new TextView(this);
        _textView.setText("Touch and drag (multiple fingers supported)!");
        _textView.setOnTouchListener(this);
        
        setContentView(_textView);
    }
    
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        int action = event.getAction() & MotionEvent.ACTION_MASK;
        int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;
        int pointerId = event.getPointerId(pointerIndex);
        
        switch (action)
        {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_POINTER_DOWN:
            _touched[pointerId] = true;
            _x[pointerId] = (int)event.getX(pointerIndex);
            _y[pointerId] = (int)event.getY(pointerIndex);
            break;
            
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_POINTER_UP:
        case MotionEvent.ACTION_CANCEL:
            _touched[pointerId] = false;
            _x[pointerId] = (int)event.getX(pointerIndex);
            _y[pointerId] = (int)event.getY(pointerIndex);
            break;
            
        case MotionEvent.ACTION_MOVE:
            int pointerCount = event.getPointerCount();
            for (int i = 0; i < pointerCount; i++)
            {
                pointerIndex = i;
                pointerId = event.getPointerId(pointerIndex);
                _x[pointerId] = (int)event.getX(pointerIndex);
                _y[pointerId] = (int)event.getY(pointerIndex);
            }
            break;
        }
        
        updateTextView();
        
        return true;
    }
}
